import { app } from 'electron'
import log from 'electron-log/main'
import path from 'path'
import * as fs from 'fs'
import global from './global'
const initLog = () => {
  log.initialize()

  // 配置控制台输出，解决中文乱码问题
  log.transports.console.format = '{h}:{i}:{s} > {text}'
  
  // 在 Windows 系统上禁用控制台输出，避免编码问题
  if (process.platform === 'win32') {
    log.transports.console.level = false
  }

  log.transports.file.resolvePathFn = () => {
    try {
      const logDir = path.join(global.localPath, 'logs')

      // 确保日志目录存在 - 改为异步
      if (!fs.existsSync(logDir)) {
        fs.mkdirSync(logDir, { recursive: true })
      }

      const filePath = path.join(logDir, `main.log`)

      if (!fs.existsSync(filePath)) {
        fs.writeFileSync(filePath, '')
      }

      return filePath
    } catch (error) {
      console.error('日志文件路径解析失败:', error)
      return path.join(app.getPath('temp'), `db-${Date.now()}.log`)
    }
  }

  log.transports.file.maxSize = 20 * 1024 * 1024
  log.transports.file.format = '{h}:{i}:{s} > {text}'
}

export default log
export { initLog } // 导出setter方法
